<template>
	<view class="storage-status">
		<text class="status-text">{{ statusText }}</text>
		<view v-if="!isEncrypted" class="encrypt-notice">
			<text class="notice-text">⚠️ 数据未加密，建议设置加密密钥</text>
			<button class="encrypt-btn" @click="setupEncryption">设置加密</button>
		</view>
		<view v-else class="encrypt-info">
			<text class="info-text">🔒 数据已加密</text>
			<button class="view-key-btn" @click="viewEncryptionKey">查看密钥</button>
			<button class="change-key-btn" @click="changeEncryptionKey">修改密钥</button>
		</view>
	</view>
</template>

<script>
// 简单的加密工具类
class CryptoUtils {
	// 生成随机密钥
	static generateKey(length = 32) {
		const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*'
		let result = ''
		for (let i = 0; i < length; i++) {
			result += chars.charAt(Math.floor(Math.random() * chars.length))
		}
		return result
	}
	
	// 安全的 Base64 编码（支持 Unicode）
	static safeBase64Encode(str) {
		try {
			return btoa(encodeURIComponent(str))
		} catch (error) {
			return btoa(unescape(encodeURIComponent(str)))
		}
	}
	
	// 安全的 Base64 解码（支持 Unicode）
	static safeBase64Decode(str) {
		try {
			return decodeURIComponent(atob(str))
		} catch (error) {
			return decodeURIComponent(escape(atob(str)))
		}
	}
	
	// 简单的异或加密
	static encrypt(text, key) {
		if (!text || !key) return text
		
		let result = ''
		for (let i = 0; i < text.length; i++) {
			const charCode = text.charCodeAt(i)
			const keyChar = key.charCodeAt(i % key.length)
			result += String.fromCharCode(charCode ^ keyChar)
		}
		return this.safeBase64Encode(result)
	}
	
	// 解密
	static decrypt(encryptedText, key) {
		if (!encryptedText || !key) return encryptedText
		
		try {
			const decoded = this.safeBase64Decode(encryptedText)
			let result = ''
			for (let i = 0; i < decoded.length; i++) {
				const charCode = decoded.charCodeAt(i)
				const keyChar = key.charCodeAt(i % key.length)
				result += String.fromCharCode(charCode ^ keyChar)
			}
			return result
		} catch (error) {
			console.error('解密失败:', error)
			return encryptedText
		}
	}
	
	// 生成哈希值用于验证
	static hash(text) {
		let hash = 0
		if (text.length === 0) return hash.toString()
		for (let i = 0; i < text.length; i++) {
			const char = text.charCodeAt(i)
			hash = ((hash << 5) - hash) + char
			hash = hash & hash
		}
		return hash.toString()
	}
	
	// 修改版本检测方法
	static detectDataVersion(data) {
		// 检查密码字段是否被加密（Base64格式）
		if (data.password && data.password.length > 10 && /^[A-Za-z0-9+/=]+$/.test(data.password)) {
			return 'v1' // 旧版本：密码字段被加密
		}
		return 'v2' // 新版本：密码字段未加密
	}
	
	// 修改兼容性解密方法
	static decryptCompatible(data, key) {
		const version = this.detectDataVersion(data)
		
		if (version === 'v1') {
			// 旧版本：解密密码字段
			return {
				...data,
				title: data.title || '',
				username: data.username || '',
				password: this.decrypt(data.password, key),
				remark: data.remark || ''
			}
		} else {
			// 新版本：密码字段未加密
			return {
				...data,
				title: data.title || '',
				username: data.username || '',
				password: data.password || '',
				remark: data.remark || ''
			}
		}
	}
	
	// 修改兼容性加密方法
	static encryptCompatible(data, key) {
		return {
			...data,
			title: data.title || '',
			username: data.username || '',
			password: this.encrypt(data.password, key), // 加密密码字段
			remark: data.remark || ''
		}
	}
}

export default {
	name: 'PasswordStorage',
	data() {
		return {
			statusText: '存储系统初始化中...',
			isReady: false,
			isEncrypted: false,
			encryptionKey: '',
			keyHash: ''
		}
	},
	mounted() {
		this.initStorage()
	},
	methods: {
		// 初始化存储系统
		async initStorage() {
			try {
				// 检查加密状态
				await this.checkEncryptionStatus()
				
				// 检查存储是否可用
				await this.testStorage()
				
				this.statusText = this.isEncrypted ? '加密存储系统就绪' : '存储系统就绪'
				this.isReady = true
				this.$emit('storage-ready')
				
			} catch (error) {
				console.error('存储系统初始化失败:', error)
				this.statusText = '存储系统初始化失败'
				this.$emit('storage-error', error.message)
			}
		},
		
		// 检查加密状态
		async checkEncryptionStatus() {
			try {
				const keyHash = uni.getStorageSync('password_key_hash')
				const encryptionKey = uni.getStorageSync('password_encryption_key')
				
				if (keyHash && encryptionKey) {
					this.encryptionKey = encryptionKey
					this.keyHash = keyHash
					this.isEncrypted = true
					this.statusText = '加密存储系统初始化中...'
				} else {
					this.isEncrypted = false
					this.statusText = '存储系统初始化中...（未加密）'
				}
			} catch (error) {
				console.error('检查加密状态失败:', error)
				this.isEncrypted = false
			}
		},
		
		// 测试存储是否可用
		async testStorage() {
			return new Promise((resolve, reject) => {
				try {
					// 测试写入
					uni.setStorageSync('_test_storage', 'test')
					// 测试读取
					const testValue = uni.getStorageSync('_test_storage')
					if (testValue === 'test') {
						// 清理测试数据
						uni.removeStorageSync('_test_storage')
						resolve()
					} else {
						reject(new Error('存储测试失败'))
					}
				} catch (error) {
					reject(new Error('存储系统不可用'))
				}
			})
		},
		
		// 设置加密
		setupEncryption() {
			uni.showActionSheet({
				itemList: ['自动生成安全密钥', '手动输入密钥'],
				success: (res) => {
					if (res.tapIndex === 0) {
						this.generateAndSetKey()
					} else {
						this.manualInputKey()
					}
				}
			})
		},
		
		// 自动生成并设置密钥
		generateAndSetKey() {
			const generatedKey = CryptoUtils.generateKey(32)
			
			uni.showModal({
				title: '自动生成安全密钥',
				content: `已为您生成32位安全密钥：\n\n${generatedKey}\n\n请妥善保存此密钥，丢失后将无法恢复数据！`,
				confirmText: '确认使用',
				cancelText: '重新生成',
				success: (res) => {
					if (res.confirm) {
						this.setEncryptionKey(generatedKey)
					} else {
						this.generateAndSetKey()
					}
				}
			})
		},
		
		// 手动输入密钥
		manualInputKey() {
			uni.showModal({
				title: '手动输入加密密钥',
				content: '请输入加密密钥（建议32位以上，包含大小写字母、数字和特殊字符）',
				editable: true,
				placeholderText: '请输入密钥',
				success: (res) => {
					if (res.confirm && res.content) {
						if (res.content.length < 8) {
							uni.showToast({ title: '密钥长度至少8位', icon: 'none' })
							return
						}
						this.setEncryptionKey(res.content)
					}
				}
			})
		},
		
		// 查看加密密钥
		viewEncryptionKey() {
			uni.showModal({
				title: '当前加密密钥',
				content: `您的加密密钥：\n\n${this.encryptionKey}\n\n请妥善保管，不要泄露给他人！`,
				showCancel: false,
				confirmText: '我知道了'
			})
		},
		
		// 修改加密密钥
		changeEncryptionKey() {
			uni.showActionSheet({
				itemList: ['自动生成新密钥', '手动输入新密钥'],
				success: (res) => {
					if (res.tapIndex === 0) {
						this.generateAndChangeKey()
					} else {
						this.manualChangeKey()
					}
				}
			})
		},
		
		// 自动生成并修改密钥
		generateAndChangeKey() {
			const newKey = CryptoUtils.generateKey(32)
			
			uni.showModal({
				title: '生成新密钥',
				content: `新密钥：\n\n${newKey}\n\n确认使用新密钥吗？系统将重新加密所有数据。`,
				confirmText: '确认',
				cancelText: '取消',
				success: (res) => {
					if (res.confirm) {
						this.migrateEncryptionKey(newKey)
					}
				}
			})
		},
		
		// 手动修改密钥
		manualChangeKey() {
			uni.showModal({
				title: '输入新密钥',
				content: '请输入新的加密密钥（建议32位以上）',
				editable: true,
				placeholderText: '请输入新密钥',
				success: (res) => {
					if (res.confirm && res.content) {
						if (res.content.length < 8) {
							uni.showToast({ title: '密钥长度至少8位', icon: 'none' })
							return
						}
						this.migrateEncryptionKey(res.content)
					}
				}
			})
		},
		
		// 迁移加密密钥（重新加密所有数据）
		async migrateEncryptionKey(newKey) {
			try {
				if (!this.encryptionKey) {
					uni.showToast({ title: '当前密钥无效', icon: 'none' })
					return
				}
				
				uni.showLoading({ title: '正在重新加密数据...' })
				
				const encryptedPasswords = this.getAllPasswordsSync()
				
				if (encryptedPasswords.length === 0) {
					this.encryptionKey = newKey
					this.keyHash = CryptoUtils.hash(newKey)
					uni.setStorageSync('password_key_hash', this.keyHash)
					uni.setStorageSync('password_encryption_key', newKey)
					uni.hideLoading()
					uni.showToast({ title: '密钥修改成功', icon: 'success' })
					return
				}
				
				// 分别处理每个密码项
				const processedPasswords = encryptedPasswords.map(p => {
					const version = CryptoUtils.detectDataVersion(p)
					
					if (version === 'v1') {
						// 旧版本：需要解密密码字段
						const decryptedPassword = CryptoUtils.decrypt(p.password, this.encryptionKey)
						return {
							...p,
							password: decryptedPassword
						}
					} else {
						// 新版本：密码字段未加密，直接使用
						return p
					}
				})
				
				// 验证解密是否成功
				const isValidDecryption = processedPasswords.every(p => 
					p.title && p.username && p.password && 
					p.title.length > 0 && p.username.length > 0 && p.password.length > 0
				)
				
				if (!isValidDecryption) {
					uni.hideLoading()
					uni.showModal({
						title: '解密失败',
						content: '当前密钥可能不正确，无法解密现有数据。请确认密钥后重试。',
						showCancel: false
					})
					return
				}
				
				// 设置新密钥
				this.encryptionKey = newKey
				this.keyHash = CryptoUtils.hash(newKey)
				
				// 使用新密钥重新加密所有密码字段
				const reEncryptedPasswords = processedPasswords.map(p => ({
					...p,
					password: CryptoUtils.encrypt(p.password, newKey)
				}))
				
				uni.setStorageSync('passwords', reEncryptedPasswords)
				uni.setStorageSync('password_key_hash', this.keyHash)
				uni.setStorageSync('password_encryption_key', newKey)
				
				uni.hideLoading()
				uni.showToast({ title: '密钥修改成功', icon: 'success' })
				
			} catch (error) {
				uni.hideLoading()
				console.error('密钥迁移失败:', error)
				uni.showModal({
					title: '迁移失败',
					content: '密钥修改失败，数据可能已损坏。建议重新设置密钥。',
					showCancel: false
				})
			}
		},
		
		// 设置加密密钥
		setEncryptionKey(key) {
			if (!key || key.length < 8) {
				uni.showToast({ title: '密钥长度至少8位', icon: 'none' })
				return
			}
			
			this.encryptionKey = key
			this.keyHash = CryptoUtils.hash(key)
			
			// 保存密钥哈希和密钥
			uni.setStorageSync('password_key_hash', this.keyHash)
			uni.setStorageSync('password_encryption_key', key)
			
			this.isEncrypted = true
			this.statusText = '加密已启用'
			
			uni.showToast({ title: '加密设置成功', icon: 'success' })
		},
		
		// 验证加密密钥
		verifyEncryptionKey() {
			return new Promise((resolve, reject) => {
				if (!this.isEncrypted) {
					resolve()
					return
				}
				
				try {
					const passwords = this.getAllPasswordsSync()
					if (passwords.length > 0) {
						// 找到第一个加密的密码进行验证
						const encryptedPassword = passwords.find(p => CryptoUtils.detectDataVersion(p) === 'v1')
						
						if (encryptedPassword) {
							const decryptedPassword = CryptoUtils.decrypt(encryptedPassword.password, this.encryptionKey)
							if (decryptedPassword && decryptedPassword.length > 0) {
								resolve()
								return
							}
						} else {
							// 没有加密数据，直接通过
							resolve()
							return
						}
					}
				} catch (error) {
					console.error('密钥验证失败:', error)
				}
				
				uni.showModal({
					title: '验证加密密钥',
					content: '请输入加密密钥以访问数据',
					editable: true,
					placeholderText: '请输入密钥',
					success: (res) => {
						if (res.confirm && res.content) {
							const inputHash = CryptoUtils.hash(res.content)
							if (inputHash === this.keyHash) {
								try {
									const passwords = this.getAllPasswordsSync()
									const encryptedPassword = passwords.find(p => CryptoUtils.detectDataVersion(p) === 'v1')
									
									if (encryptedPassword) {
										const decryptedPassword = CryptoUtils.decrypt(encryptedPassword.password, res.content)
										if (decryptedPassword && decryptedPassword.length > 0) {
											this.encryptionKey = res.content
											resolve()
										} else {
											uni.showToast({ title: '密钥错误', icon: 'none' })
											reject(new Error('密钥验证失败'))
										}
									} else {
										this.encryptionKey = res.content
										resolve()
									}
								} catch (error) {
									uni.showToast({ title: '密钥错误', icon: 'none' })
									reject(new Error('密钥验证失败'))
								}
							} else {
								uni.showToast({ title: '密钥错误', icon: 'none' })
								reject(new Error('密钥验证失败'))
							}
						} else {
							reject(new Error('用户取消'))
						}
					}
				})
			})
		},
		
		// 加密数据
		encryptData(data) {
			if (!this.isEncrypted || !this.encryptionKey) {
				return data
			}
			
			return CryptoUtils.encryptCompatible(data, this.encryptionKey)
		},
		
		// 解密数据
		decryptData(data) {
			if (!this.isEncrypted || !this.encryptionKey) {
				return data
			}
			
			return CryptoUtils.decryptCompatible(data, this.encryptionKey)
		},
		
		// 保存密码
		savePassword(passwordData) {
			return new Promise((resolve, reject) => {
				if (!this.isReady) {
					reject(new Error('存储系统未就绪'))
					return
				}
				
				try {
					const passwords = this.getAllPasswordsSync()
					const newId = Date.now()
					const newPassword = {
						id: newId,
						...this.encryptData(passwordData),
						created_at: new Date().toISOString(),
						updated_at: new Date().toISOString()
					}
					passwords.unshift(newPassword)
					uni.setStorageSync('passwords', passwords)
					resolve(newId)
				} catch (error) {
					reject(error)
				}
			})
		},
		
		// 获取所有密码
		getAllPasswords() {
			return new Promise((resolve, reject) => {
				if (!this.isReady) {
					reject(new Error('存储系统未就绪'))
					return
				}
				
				try {
					const passwords = this.getAllPasswordsSync()
					// 解密数据
					const decryptedPasswords = passwords.map(p => this.decryptData(p))
					resolve(decryptedPasswords)
				} catch (error) {
					reject(error)
				}
			})
		},
		
		// 同步获取所有密码
		getAllPasswordsSync() {
			const passwords = uni.getStorageSync('passwords') || []
			return passwords
		},
		
		// 更新密码
		updatePassword(id, passwordData) {
			return new Promise((resolve, reject) => {
				if (!this.isReady) {
					reject(new Error('存储系统未就绪'))
					return
				}
				
				try {
					const passwords = this.getAllPasswordsSync()
					const index = passwords.findIndex(p => p.id == id)
					if (index !== -1) {
						passwords[index] = {
							...passwords[index],
							...this.encryptData(passwordData),
							updated_at: new Date().toISOString()
						}
						uni.setStorageSync('passwords', passwords)
					}
					resolve()
				} catch (error) {
					reject(error)
				}
			})
		},
		
		// 删除密码
		deletePassword(id) {
			return new Promise((resolve, reject) => {
				if (!this.isReady) {
					reject(new Error('存储系统未就绪'))
					return
				}
				
				try {
					const passwords = this.getAllPasswordsSync()
					const filteredPasswords = passwords.filter(p => p.id != id)
					uni.setStorageSync('passwords', filteredPasswords)
					resolve()
				} catch (error) {
					reject(error)
				}
			})
		},
		
		// 搜索密码
		searchPasswords(keyword) {
			return new Promise((resolve, reject) => {
				if (!this.isReady) {
					reject(new Error('存储系统未就绪'))
					return
				}
				
				try {
					const passwords = this.getAllPasswordsSync()
					const decryptedPasswords = passwords.map(p => this.decryptData(p))
					const filteredPasswords = decryptedPasswords.filter(p => 
						p.title.includes(keyword) || p.username.includes(keyword)
					)
					resolve(filteredPasswords)
				} catch (error) {
					reject(error)
				}
			})
		},
		
		// 清空所有数据
		clearAllData() {
			return new Promise((resolve, reject) => {
				if (!this.isReady) {
					reject(new Error('存储系统未就绪'))
					return
				}
				
				try {
					uni.removeStorageSync('passwords')
					resolve()
				} catch (error) {
					reject(error)
				}
			})
		},
		
		// 导出数据
		exportData() {
			return new Promise((resolve, reject) => {
				if (!this.isReady) {
					reject(new Error('存储系统未就绪'))
					return
				}
				
				this.getAllPasswords().then(passwords => {
					const exportData = {
						version: '1.0',
						exportTime: new Date().toISOString(),
						isEncrypted: this.isEncrypted,
						passwords: passwords
					}
					resolve(exportData)
				}).catch(reject)
			})
		},
		
		// 导入数据
		importData(data) {
			return new Promise((resolve, reject) => {
				if (!this.isReady) {
					reject(new Error('存储系统未就绪'))
					return
				}
				
				if (!data.passwords || !Array.isArray(data.passwords)) {
					reject(new Error('数据格式错误'))
					return
				}
				
				try {
					const passwords = data.passwords.map(p => 
						data.isEncrypted ? p : this.encryptData(p)
					)
					uni.setStorageSync('passwords', passwords)
					resolve()
				} catch (error) {
					reject(error)
				}
			})
		}
	}
}
</script>

<style>
.storage-status {
	padding: 10rpx 20rpx;
	background: #f0f0f0;
	border-radius: 8rpx;
	margin: 10rpx 0;
}

.status-text {
	font-size: 24rpx;
	color: #666;
	display: block;
	margin-bottom: 10rpx;
}

.encrypt-notice {
	display: flex;
	justify-content: space-between;
	align-items: center;
	padding: 10rpx 0;
	border-top: 1rpx solid #ddd;
}

.notice-text {
	font-size: 22rpx;
	color: #ff9500;
}

.encrypt-btn {
	font-size: 20rpx;
	padding: 6rpx 12rpx;
	background: #ff9500;
	color: #fff;
	border-radius: 4rpx;
	border: none;
}

.encrypt-info {
	display: flex;
	justify-content: space-between;
	align-items: center;
	padding: 10rpx 0;
	border-top: 1rpx solid #ddd;
}

.info-text {
	font-size: 22rpx;
	color: #28a745;
}

.view-key-btn, .change-key-btn {
	font-size: 20rpx;
	padding: 6rpx 12rpx;
	margin-left: 10rpx;
	border-radius: 4rpx;
	border: none;
}

.view-key-btn {
	background: #007bff;
	color: #fff;
}

.change-key-btn {
	background: #6c757d;
	color: #fff;
}
</style> 